<template>
  <view class="goods-list" :style="listHeight ?{height: this.listHeight }:{height: `${this.height}%` }">
    <view class="table-header" v-if="columns">
      <view class="col" :class="index==0?'name':index==columns.length-1?'action':''" v-for="(item,index) in columns">
        <view>{{ item.title }}</view>
      </view>
    </view>

    <scroll-view
        scroll-y
        enhanced
        :lower-threshold="5"
        style="height: 100%;flex: 1;"
        @scrolltolower="loadMore"
        :refresher-enabled="enabled"
        :refresher-triggered="nTriggered"
        @refresherrefresh="refreshData"
    >
      <slot name="header"/>
      <slot name="item" v-for="(item, index) in dataList" :item="item" :index="index" @click="itemClick(item)"
            class="list-footer-placeholder"/>
      <!-- 加载状态 -->
      <view class="loading-status" v-if="isLoad || dataList.length == 0">
        <image style="
               width: 40vw;
        height: 40vw;
        max-width: 420rpx;
        max-height: 320rpx;
        object-fit: contain;
        transition: opacity 0.3s;
        flex: 1;
        margin-left: 27%;
        min-width: 100rpx;
        min-height: 100rpx;
        align-self: center;
      " v-if="dataList.length === 0" src="../../static/icon/nolist.png"></image>
        <uni-load-more :status="loadingStatus"/>
      </view>
      <view style="min-height: calc(270px);"/>
    </scroll-view>

  </view>
</template>

<script>
import UniLoadMore from "../../uni_modules/uni-load-more/components/uni-load-more/uni-load-more.vue";
import {JeecgListMixin} from "../../utils/JeecgListMixin";
import _ from "lodash";

export default {
  name: "aJList",
  mixins: [JeecgListMixin],
  components: {UniLoadMore},
  props: {
    /**
     * 列表高度比例
     */
    height: Number,
    /**
     * 是否上拉
     */
    enabled: {
      type: Boolean,
      default: true
    },
    /**
     * 是否下滑
     */
    triggered: {
      type: Boolean,
      default: true
    },
    /**
     * 访问地址
     */
    apiUrl: String,
    /**
     * 是否有标题栏
     */
    columns: Array,
    /**
     * 是否初始化加载数据
     */
    isLoadData: {
      type: Boolean,
      default: true
    },
    /**
     * 是否有展开功能
     */
    isExpanded: {
      type: Boolean,
      default: false
    },
    /**
     * 是否显示统计行
     */
    isTotalRow: {
      type: Boolean,
      default: false
    },
    /**
     * 查询分组条件
     */
    groupBy: String,
    /**
     * 手动赋值数据
     */
    data: Array,
    /**
     * 是否显示加载状态
     */
    isLoad: {
      type: Boolean,
      default: true
    },
    /**
     * 是否有选中状态
     */
    isChecked: {
      type: Boolean,
      default: false
    },
    parentRef: {
      type: Object,
      default: null
    },
    className: {
      type: String,
      default: ''
    },
    listHeight: '',
  },
  data() {
    return {
      tempData: [], // 存储临时数据
      nTriggered: true,
      dataList: [],
      loadingStatus: 'more',
      url: {
        list: this.apiUrl
      },
    }
  },
  watch: {
    triggered: {
      handler(newVal) {
        this.nTriggered = newVal;
      },
      deep: true,
      immediate: true,
    },
    data: {
      handler(newVal) {
        if (newVal) {
          this.dataList = _.cloneDeep(newVal);
          this.$nextTick(() => {
            this.loadingStatus = this.dataList.length < this.ipagination.pageSize ? 'noMore' : 'more';
          })
        }
      },
      deep: true,
      immediate: true,
    },
    dataSource: {
      handler(newVal) {
        if (this.ipagination.current === 1) {
          this.tempData = []
        } else {
          if (newVal.length <= 0) {
            return
          }
        }
        this.updateList(newVal)
        this.$emit('loading', this.dataList);
      },
      deep: true,
      immediate: true,
    },
  }
  ,
  methods: {
    /**
     * 统一更新列表方法
     * @param newVal
     */
    updateList(newVal) {
      if (newVal.length <= 0) {
        this.tempData = []
      } else {
        //是否增加总计行
        let totalRow = []
        if (this.isTotalRow) {
          let inventoryQuantity = 0
          let totalInventoryQuantity = 0
          if (newVal != null && newVal.length > 0) {
            inventoryQuantity = newVal[0].inventory
            totalInventoryQuantity = newVal[0].totalInventory
          }
          // 添加或更新合计行
          totalRow = {
            goodsTitle: "合计",
            inventoryQuantity: inventoryQuantity,
            totalInventoryQuantity: totalInventoryQuantity,
            isTotal: true,
            expanded: null,
            childrenList: []
          };
        }
        let newData = []
        if (this.ipagination.current > 1) {
          const ids = this.dataList.map(i => i.id || i.specsId || i.goodsId)
          if (ids) {
            newData = newVal.filter(obj => !ids.includes(obj.id || obj.specsId || obj.goodsId));
          }
        } else {
          newData = newVal
          if (this.isTotalRow && this.ipagination.current == 1 && totalRow) {
            this.tempData.push(totalRow)
          }
        }
        if (this.isExpanded && newData.length > 0) {
          newData = newData.map(obj => ({...obj, expanded: false}))
        }
        if (this.isChecked && newData.length > 0) {
          newData = newData.map(obj => ({...obj, checked: false}))
        }
        // 或改用 concat 创建新数组
        this.tempData.push(...newData);
      }
      this.dataList = _.cloneDeep(this.tempData)
      this.$set(this, "dataList", _.cloneDeep(this.tempData))
      this.$nextTick(() => {
        this.loadingStatus = this.dataList.length >= this.ipagination.total ? 'noMore' : 'more';
      })
    },
    /**
     * 加载的状态
     * @param loadingStatus
     */
    lodData(loadingStatus) {
      this.dataList = []
      this.loadingStatus = loadingStatus
    },
    /**
     * 查询方法
     */
    searchQueryData() {
      this.dataSource = []
      this.searchQuery()
    },
    /**
     * 删除项
     * @param index
     */
    deleteItem(index) {
      this.dataList.splice(index, 1);
    },
    /**
     * 项点击
     * @param item
     */
    itemClick(item) {
      this.$emit('click', item);
    },
    /**
     * 上滑
     */
    loadMore() {
      if (this.loadingStatus === 'noMore') return;
      this.ipagination.current++;
      this.loadData()
    },
    /**
     * 下拉
     */
    refreshData() {
      this.nTriggered = true;
      this.loadData(1)
      setTimeout(() => {
        uni.stopPullDownRefresh(); // 必要操作
        this.nTriggered = false; // 必须确保状态重置
      }, 500);
    },
    /**
     * 折叠状态
     * @param id
     */
    handleItemUpdate(id) {
      this.dataSource.forEach((item, _index) => {
        if (item.id != id) {
          item.expanded = false
        } else {
          item.expanded = true
        }
        return item
      })
    },
  },
  mounted() {
    if (this.isLoadData) {
      this.loadData(1);
    }
  },
}
</script>

<style scoped>

.goods-list {
  display: flex;
  flex-direction: column;
  padding: 0.5rem;
  height: 100%; /* 覆盖原有高度 */
  overflow: visible; /* 解除父容器限制 */


  .table-header {
    display: flex;
    align-items: center;
    padding: 15rpx;
    background-color: #fff;
    border-bottom: 1rpx solid #eee;

    .col {
      flex: 1;
      text-align: center;
      font-size: 22rpx;
      color: #333;

      &.name {
        flex: 2;
        text-align: left;
      }

      &.action {
        flex: 0.8;
      }
    }
  }

  scroll-view {
    flex: 1;
    /* 新增布局修正 */
    display: flex;
    flex-direction: column;
    min-height: 300px; /* 防止空数据时高度塌陷 */

    .loading-status {
      min-height: 10vh; /* 确保最小高度 */
      justify-content: center !important; /* 主轴居中 */
      align-items: center !important; /* 交叉轴居中 */
    }

    .list-footer-placeholder {
      height: 110vh;
    }
  }
}


</style>
